package com.ruoyi.web.controller.module.commonInfo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.commonInfo.CommonInfo;
import com.ruoyi.system.domain.module.commonInfo.CommonInfoImg;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.service.module.commonInfo.ICommonInfoImgService;
import com.ruoyi.system.service.module.commonInfo.ICommonInfoService;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.web.controller.common.BaseController;
import com.vdurmont.emoji.EmojiParser;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 跳蚤市场信息Controller
 *
 * @author ruoyi
 * @date 2021-08-29
 */
@Validated
@Api(value = "跳蚤市场信息控制器", tags = {"跳蚤市场信息管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/commonInfo")
public class CommonInfoController extends BaseController {

    private final ICommonInfoService fleaInfoService;
    private final ICommonInfoImgService commonInfoImgService;
	private final IEstateService estateService;
	private final IPropertyService propertyService;
    private final IWxUserService wxUserService;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;

    /**
     * 查询跳蚤市场信息列表
     */
    @ApiOperation("查询跳蚤市场信息列表")
    @PreAuthorize("@ss.hasPermi('module:commInfo:list')")
    @GetMapping("/list")
    public TableDataInfo<CommonInfo> list(@Validated CommonInfo commonInfo) {

        SysUser sysUser = getUser();
        QueryWrapper<CommonInfo> qw = new QueryWrapper<>();
        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        }

		if(commonInfo.getInfoType() != null){
			qw.eq("info_type",commonInfo.getInfoType());
		}
		if(StrUtil.isNotEmpty(commonInfo.getCommonTitle())){
			qw.like("common_title",commonInfo.getCommonTitle());
		}

        if(StrUtil.isNotEmpty(commonInfo.getBeginDate())){
            qw.between("create_time",commonInfo.getBeginDate() + " 00:00:00",commonInfo.getEndDate() + " 23:59:59");
        }

        qw.orderByDesc("create_time");
        TableDataInfo<CommonInfo> td = PageUtils.buildDataInfo(fleaInfoService.page(PageUtils.buildPage(),qw));
        List<CommonInfo> list = td.getRows();
        list.forEach(info->{
            List<String> imgUrls = new ArrayList<>();
//            if(StrUtil.isNotEmpty(info.getImgUrl())){
//                String[] imgs = info.getImgUrl().split(",");
//                for (String img : imgs){
//                    imgUrls.add(imgUrl + img);
//                }
//            }
//            info.setImgUrls(imgUrls);
            WxUser wxUser = wxUserService.findById(info.getUserId());
            if(wxUser!=null){
				info.setFaceUrl(wxUser.getFaceUrl());
				if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
					info.setFaceUrl(imgUrl + wxUser.getFaceUrl());
				}
            }

            if(StrUtil.isNotEmpty(info.getNickName())){
                info.setNickName(EmojiParser.parseToUnicode(info.getNickName()));
            }

			Estate estate = estateService.findById(info.getEstateId());
			if(estate!=null){
				info.setEstateName(estate.getEstateName());
			}

			Property property = propertyService.findById(info.getPropertyId());
			if(property!=null){
				info.setPropertyName(property.getPropertyName());
			}

            QueryWrapper<CommonInfoImg> qwImg =new QueryWrapper<>();
            qwImg.eq("info_id",info.getId());
            List<CommonInfoImg> imgs = commonInfoImgService.list(qwImg);
            if(CollUtil.isNotEmpty(imgs)){
                for (CommonInfoImg img : imgs){
                    imgUrls.add(imgUrl + img.getImgUrl());
                    img.setImgUrl(imgUrl + img.getImgUrl());
                }
                info.setImgs(imgs);
                info.setImgUrls(imgUrls);
            }
        });
        return td;
    }

    /**
     * 获取跳蚤市场信息详细信息
     */
    @ApiOperation("获取跳蚤市场信息详细信息")
    @PreAuthorize("@ss.hasPermi('module:commInfo:query')")
    @GetMapping("/{id}")
    public AjaxResult<CommonInfo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        CommonInfo commonInfo = fleaInfoService.getById(id);
        if(commonInfo != null){
            String imgUrlPaths = "";
            QueryWrapper<CommonInfoImg> qwImg =new QueryWrapper<>();
            qwImg.eq("info_id",commonInfo.getId());
            qwImg.orderByAsc("create_time");
            List<CommonInfoImg> imgs = commonInfoImgService.list(qwImg);
            if(CollUtil.isNotEmpty(imgs)){
                for (CommonInfoImg img : imgs){
                    imgUrlPaths += imgUrl + img.getImgUrl() + ",";
                    img.setImgUrl(imgUrl + img.getImgUrl());
                }
                commonInfo.setImgs(imgs);
            }
            if(StrUtil.isNotEmpty(imgUrlPaths)){
                imgUrlPaths = imgUrlPaths.substring(0,imgUrlPaths.length() -1 );
            }
            commonInfo.setImgUrlPaths(imgUrlPaths);
        }
        return AjaxResult.success(commonInfo);
    }

    /**
     * 新增跳蚤市场信息
     */
    @ApiOperation("新增跳蚤市场信息")
    @PreAuthorize("@ss.hasPermi('module:commInfo:add')")
    @Log(title = "跳蚤市场信息", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody CommonInfo commonInfo) {
        if(StrUtil.isNotEmpty(commonInfo.getCommonTitle())){
            commonInfo.setCommonTitle(EmojiParser.parseToAliases(commonInfo.getCommonTitle()));
        }
        if(StrUtil.isNotEmpty(commonInfo.getContent())){
            commonInfo.setContent(EmojiParser.parseToAliases(commonInfo.getContent()));
        }
        return toAjax(fleaInfoService.save(commonInfo) ? 1 : 0);
    }

    /**
     * 修改跳蚤市场信息
     */
    @ApiOperation("修改跳蚤市场信息")
    @PreAuthorize("@ss.hasPermi('module:commInfo:edit')")
    @Log(title = "跳蚤市场信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody CommonInfo commonInfo) {
        if(StrUtil.isNotEmpty(commonInfo.getCommonTitle())){
            commonInfo.setCommonTitle(EmojiParser.parseToAliases(commonInfo.getCommonTitle()));
        }
        if(StrUtil.isNotEmpty(commonInfo.getContent())){
            commonInfo.setContent(EmojiParser.parseToAliases(commonInfo.getContent()));
        }
        boolean bl = fleaInfoService.updateById(commonInfo);
        if(bl){
            List<CommonInfoImg> delImg = new ArrayList<>();
            List<CommonInfoImg> imgs = commonInfo.getImgs();

            QueryWrapper<CommonInfoImg> qw = new QueryWrapper<>();
            qw.eq("info_id",commonInfo.getId());
            List<CommonInfoImg> infoImgs = commonInfoImgService.list(qw);
            if(CollUtil.isNotEmpty(infoImgs)){
                for (CommonInfoImg img : infoImgs){
                    int isHas = 0;
                    for (CommonInfoImg img1 : imgs){
                        if(img1.getId()!=null && img.getId().equals(img1.getId())){//存在
                            isHas = 1;
                        }
                    }
                    if(isHas == 0){
                        delImg.add(img);
                    }
                }
            }

            if(CollUtil.isNotEmpty(imgs)){
                for (CommonInfoImg img : imgs){
                    if(img.getId() == null){
                        img.setInfoId(commonInfo.getId());
                        img.setCreateTime(new Date());
                        img.setSort(1);
                        img.setImgType("png");
                        commonInfoImgService.save(img);
                    }
                }
            }
            if(CollUtil.isNotEmpty(delImg)){
                for (CommonInfoImg img : delImg){
                    commonInfoImgService.removeById(img.getId());
                }
            }
        }
        return toAjax(bl? 1 : 0);
    }

    /**
     * 删除跳蚤市场信息
     */
    @ApiOperation("删除跳蚤市场信息")
    @PreAuthorize("@ss.hasPermi('module:commInfo:remove')")
    @Log(title = "跳蚤市场信息" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(fleaInfoService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
